package com.gitee.baqkft.code.core.util;

import java.io.*;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * FreeMarker工具集
 * @author chenmingcai
 * @date 2018年5月19日 下午5:12:21
 *
 */

public class FreemarkerUtils
{
	/**
	 * 生成配置
	 * @return
	 */
	public static Configuration defaultConfiguration()
	{
		final Configuration config = new Configuration(Configuration.VERSION_2_3_28);
		config.setDefaultEncoding("utf-8");
		config.setDateTimeFormat("yyyy-MM-dd HH:mm:ss");
		config.setNumberFormat("computer");

		return config;
	}

	/**
	 * 处理模板
	 * @param model
	 * @param tmpl
	 * @param out
	 */
	public static void process(Map<Object, Object> model, Template tmpl, OutputStream out)
	{
		try
		{
			OutputStreamWriter writer = new OutputStreamWriter(out);
			BufferedWriter oWriter = new BufferedWriter(writer);
			tmpl.process(model, oWriter);
			oWriter.flush();
			oWriter.close();
		}
		catch(IOException | TemplateException ex)
		{
			ex.printStackTrace();
		}
	}

	/**
	 * 处理模板生成字符串
	 * @param model	数据模型
	 * @param tmpl	模板
	 * @return	字符串
	 */
	public static String process(Map<Object, Object> model, Template tmpl)
	{
		StringWriter writer = new StringWriter();
		try
		{
			BufferedWriter oWriter = new BufferedWriter(writer);
			tmpl.process(model, oWriter);
			oWriter.flush();
			oWriter.close();
		}
		catch(IOException | TemplateException ex)
		{
			ex.printStackTrace();
		}

		return writer.toString();
	}

	/**
	 * 根据配置加载模板
	 * @param config
	 * @param template
	 * @return
	 */
	public static Template loadTemplate(Configuration config, String template)
	{
		Template tmpl = null;
		try
		{
			tmpl = config.getTemplate(template);
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
		return tmpl;
	}
}
